package com.third.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.third.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 唐博文
 * @version 2023.1.2
 * @date 2023/10/22 16:10 星期日
 */
@Component
public class JwtAuthorizeFilter extends OncePerRequestFilter {
    
    @Resource
    JwtUtils utils;
    
    
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String authorization=request.getHeader("Authorization");
        DecodedJWT jwt= utils.resolveJwt(authorization);
        if(jwt!=null){
            UserDetails user=utils.toUser(jwt);
            //手动授权
            UsernamePasswordAuthenticationToken authentication=
                    new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //将自己的验证信息放进去---这样就通过了
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("id",utils.toId(jwt));
        }
        filterChain.doFilter(request,response);
    }
}
